package cn.idongjia.task.excuter.shell;

import cn.idongjia.task.common.task.ExcuteResult;
import cn.idongjia.task.common.task.Result;
import cn.idongjia.task.common.task.TaskResult;
import com.lts.core.commons.utils.StringUtils;
import com.lts.core.domain.Action;
import com.lts.core.logger.Logger;
import com.lts.core.logger.LoggerFactory;
import com.lts.core.support.SystemClock;


import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by renxianlong on 16/3/31.
 */
public class ShellUtil {

    public static ShellUtil instance = new ShellUtil();

    private Logger logger = LoggerFactory.getLogger(ShellUtil.class);

    public static final String TEMP_FILEPATH = System.getProperty("user.home") + "/";;

    public static final String TEMP_FILENAME = "result.temp";

    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");

    public ExcuteResult executeShell(String shellCommand){
        if (StringUtils.isEmpty(shellCommand)) {
            return new ExcuteResult("input shell is null");
        }
        BufferedReader errorReader = null;
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer resultBuffer = new StringBuffer();
        ExcuteResult result = new ExcuteResult();
        boolean ifError = false;
        try {
            stringBuffer.append(dateFormat.format(new Date())).append("准备执行Shell命令 ").append(shellCommand).append(" \r\n");
            String[] cmd = {"/bin/sh", "-c", shellCommand};
            Process pid = Runtime.getRuntime().exec(cmd);
            if (pid != null) {
                pid.waitFor();
            } else {
                stringBuffer.append("未找到执行进程\r\n");
            }
            stringBuffer.append(dateFormat.format(new Date())).append("Shell命令执行完毕\r\n执行结果为：\r\n");
            errorReader = new BufferedReader(new InputStreamReader(pid.getErrorStream()));
            String line = null;
            while (errorReader != null && (line = errorReader.readLine()) != null){
                ifError = true;
                resultBuffer.append(line).append("\r\n");
                stringBuffer.append(line).append("\r\n");
            }
            if(!ifError){
                resultBuffer.append("SUCCESS\r\n");
                stringBuffer.append("SUCCESS\r\n");
            }
        } catch (Exception e) {
            stringBuffer.append("执行Shell命令时发生异常：\r\n").append(e.getMessage()).append("\r\n");
            result.setResult(Result.EXECUTE_FAILED);
        } finally {
            try {
                errorReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        logger.debug(stringBuffer.toString());
        result.setMsg(resultBuffer.toString());
        logger.debug("resultMsg:" +result.getMsg());
        return result;
    }

    public static ShellUtil getInstance(){
        return instance;
    }
    private ShellUtil(){

    }
}
